package com.jd.service.impl;

import com.jd.entity.Department;
import com.jd.mapper.DepartmentMapper;
import com.jd.service.DepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wangshuping
 * @since 2021-11-22
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {


    @Override
    public Object buildTree() {
        List<Department> departments = list();
        //顶级部门为-1
        List<Department> rootDepartment = departments.stream().filter(department -> null == department.getParentDeptId()).collect(Collectors.toList());
        buildTree(rootDepartment, departments);
        return rootDepartment;
    }

    private void buildTree(List<Department> rootDepartment, List<Department> departments) {
        rootDepartment.forEach(department -> {
            department.setChildren(new ArrayList<>());
            Iterator<Department> it = departments.iterator();
            while (it.hasNext()) {
                Department next = it.next();
                if (department.getId().equals(next.getParentDeptId())) {
                    department.getChildren().add(next);
                    it.remove();
                }
            }
            buildTree(department.getChildren(), departments);
        });
    }

    public static void main(String[] args) {
        Department department01 = new Department();
        department01.setId(1l);
        department01.setParentDeptId(null);


        Department department02 = new Department();
        department02.setId(2l);
        department02.setParentDeptId(null);

        Department department03 = new Department();
        department03.setId(3l);
        department03.setParentDeptId(4l);


        Department department04 = new Department();
        department04.setId(4l);
        department04.setParentDeptId(1l);

//        (1-4-3),2

        ArrayList<Department> departments = new ArrayList<>();
        departments.add(department01);
        departments.add(department02);
        departments.add(department03);
        departments.add(department04);

        List<Department> rootDepartment = departments.stream().filter(department -> department.getParentDeptId() == null).collect(Collectors.toList());
        System.out.println(rootDepartment);
        DepartmentServiceImpl service = new DepartmentServiceImpl();
        service.buildTree(rootDepartment, departments);

        System.out.println(rootDepartment);
    }


}
